//
//  JFBOrderListDataSource.m
//  ios-supplier
//
//  Created by feynmanyuan on 15/4/15.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "JFBOrderDS.h"
#import "JFBAPIClient.h"
#import "JFBMerchandiseDS.h"

@interface JFBOrderDS ()
@property (nonatomic, strong) NSMutableArray * items;
@end

@implementation JFBOrderDS
- (instancetype)initWithAttributes:(NSDictionary *)attributes {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    self.ID = [[attributes objectForKey: @"id"] isEqual: [NSNull null]] ? 0 : [[attributes objectForKey:@"id"] intValue];
    self.orderCode = [[attributes objectForKey: @"so_number"] isEqual: [NSNull null]] ? 0 : [attributes objectForKey: @"so_number"];
    self.balance_amount = [[attributes objectForKey: @"balance_amount"] isEqual: [NSNull null]] ? 0 : [NSString formatDecimal:[attributes objectForKey:@"balance_amount"]];
    
    self.address = [[attributes objectForKey: @"address_name"] isEqual: [NSNull null]] ? 0 : [attributes objectForKey: @"address_name"];
    
    NSArray * addresses = [self.address componentsSeparatedByString:@"#"];
    self.address = [NSString stringWithFormat:@"%@%@", addresses.count == 2 ? addresses[1] : addresses[0], [NSString isNilOrEmpty:[attributes objectForKey:@"address_detail"]] ? @"" :  [attributes objectForKey:@"address_detail"]];
    

    
    self.requireTime = @"";
    NSUInteger paymentType = [[attributes objectForKey:@"payment"] intValue];
    
    self.paymentOrigin = paymentType;
    self.payment = paymentType == 1 ? @"网上支付" : @"货到付款";
    

    
    self.money = [NSString formatDecimal:[attributes objectForKey:@"balance_price"]];
    
    self.createAt = [[attributes objectForKey:@"create_at"] substringToIndex:16];
    
    self.updateAt = [[attributes objectForKey:@"update_at"]  substringToIndex:16];
    self.userName = [attributes objectForKey:@"receiver"] ? [attributes objectForKey:@"receiver"] : [NSString stringWithFormat:@"jfb%lu", (unsigned long)self.ID];
    self.userMobile = [attributes objectForKey:@"receiver_phone"] ? [attributes objectForKey:@"receiver_phone"] : @"";
    self.staff = [attributes objectForKey:@"express_name"];
    self.staffMobile = [attributes objectForKey:@"express_mobile"];
    if( [self.staffMobile isEqual:[NSNull null]] ) {
        self.staffMobile = @"";
    }
    self.remark = [NSString isNilOrEmptyOrWhitespace:[attributes objectForKey:@"so_note"]] ? DefaultRemark : [attributes objectForKey:@"so_note"];
    
    self.completeAt = [[attributes objectForKey: @"update_at"] isEqual: [NSNull null]] ? 0 : [attributes objectForKey: @"update_at"];
    
    self.originMoney = [[attributes objectForKey: @"total_price"] isEqual: [NSNull null]] ? 0 : [NSString formatDecimal:[attributes objectForKey:@"total_price"]];
    
    self.carriageMoney = [[attributes objectForKey: @"freight"] isEqual: [NSNull null]] ? 0 : [NSString formatDecimal:[attributes objectForKey:@"freight"]];
    
    NSDecimalNumber * discountAmount = [NSString formatDecimal:[attributes objectForKey:@"discount_amount"]];
    
    NSDecimalNumber * couponAmount = [NSString formatDecimal:[attributes objectForKey:@"coupon_amount"]];
    self.promotionMoney = [NSString formatDecimal:[discountAmount decimalNumberByAdding:couponAmount]];
    
    self.merchandiseList = [[NSMutableArray alloc] init];
    NSInteger count = 0;
    for( NSDictionary * item in [attributes objectForKey:@"soItems"] ) {
        JFBMerchandiseDS * mds = [[JFBMerchandiseDS alloc] initWithOrderListAttributes:item];
        [self.merchandiseList addObject:mds];
//        count += mds.count;
    }
    self.totalCount = count;
    return self;
}


//加载订单列表，订单类型通过orderType来区分, 目前处理未处理，和
+ (NSURLSessionDataTask *)loadOrderList:(void (^)(NSArray *orders, NSError *error))block orderType:(NSUInteger)orderType pager:(JFBPager*)pager{
    NSDictionary * parameter = @{@"so_status":[NSNumber numberWithInteger:orderType]};
    return [[JFBAPIClient sharedClient:true] GET:@"/shop/so/list.json" parameters:parameter success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSObject * error = [JSON valueForKey:@"error"];
        if( error == [NSNull null] ) {
            NSMutableArray *result = [@[] mutableCopy];
            NSArray *response = [JSON valueForKeyPath:@"data"];
            for( NSDictionary *order in response ) {
                [result addObject:[[JFBOrderDS alloc] initWithAttributes:order]];
            }
            
            NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"updateAt" ascending:NO];
            [result sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
            
            block([NSArray arrayWithArray:result], nil);
        } else {
            block(nil, nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        block(nil, error);
    }];

    return nil;
}

//确认配送
+ (NSURLSessionDataTask *)acceptStaff:(void (^)(BOOL isSuccess, JFBOrderDS *order, NSError *error))block orderID:(NSUInteger)orderID staffID:(NSUInteger)staffID {
    
    NSDictionary *parameter = @{@"so_id":[NSNumber numberWithInteger:orderID], @"express_id":[NSNumber numberWithInteger:staffID]};
    
    return [[JFBAPIClient sharedClient:true] GET:@"/shop/so/express.json" parameters:parameter success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSObject * error = [JSON valueForKey:@"error"];
        if( error == [NSNull null] ) {
            block(true, nil, nil);
        } else {
            block(false, nil, nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        block(false, nil, error);
    }];

    return nil;
}



@end
